
import datetime
import psycopg2


class NetworkMonitoring:

    def __init__(self, config):
        self.config = config

    def build_query(self, args):
        """
        从args创建查询
        :param args:
        :return:
        """
        config = self.config
        dbname = config['monitor_database']['database']
        user = config['monitor_database']['user']
        passwd = config['monitor_database']['password']
        host = config['monitor_database']['host']
        port = config['monitor_database']['port']
        conn = psycopg2.connect(database=dbname, user=user, password=passwd, host=host, port=port)
        cur = conn.cursor()
        words = args.get('words')
        insert_time = args.get('insert_time')
        time_interval = args.get('time_interval')
        if len(insert_time) == 19:
            insert_time = insert_time[:-3]
        in_time = datetime.datetime.strptime(insert_time, '%Y-%m-%d %H:%M')
        if time_interval is None or len(time_interval) < 2:
            start_time = (in_time - datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M')
            end_time = (in_time + datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M')
        else:
            start_time = time_interval[0]
            end_time = time_interval[1]

        message = []
        for word in words:
            re_message = self.insert_db(cur, conn, word, insert_time, start_time, end_time)
            message.append(re_message)
        conn.close()
        return {'message': message}

    @staticmethod
    def build_result(result):
        return result

    @staticmethod
    def check_db(cur, word, start_time, end_time):
        cur.execute(
            "select word,start_time,end_time from network_monitoring_words WHERE word='" + word + "' and start_time<='"+start_time+"' and end_time>='"+end_time+"'")
        rows = cur.fetchall()
        if len(rows) < 1:
            return None
        else:
            return rows

    def insert_db(self, curs, con, word, insert_time, start_time, end_time):
        row = self.check_db(curs, word, start_time, end_time)
        if row is not None:
            return {'message': word + ' success add in monitor !'}
        try:
            curs.execute(
                "INSERT INTO network_monitoring_words(word,insert_time,start_time,end_time) "
                "VALUES (%s, %s, %s, %s)",
                (word, insert_time, start_time, end_time))
            con.commit()
            return {'message': word + ' success add in monitor !'}
        except Exception as sql_e:
            con.commit()
            return {'message': word + ': ' + start_time + '-' + end_time + ' : ' + str(sql_e)}
